<template>
	<div class="r-r">
		<div class="knowledge-warp-xx">
			<p>试卷预览</p>
			<el-button class="knowledge-add" @click="newTopic()">新增自建试题</el-button>	
			
		</div>
		<el-scrollbar class="knowledge-scrollbar" ref="elscrollbar">

			<div class="preview-conten-l-h">
				<h3>
					<el-input :class="{validName: valid}" v-model.trim="testName" placeholder="请输入内容" @change="setTestName" maxlength="20"></el-input>
					<p>{{tipName}}</p>
				</h3>
				<!-- <p>满分 {{totalNumber}}分         <span v-show="testTime">完成时间{{testTime? testTime: 0}}分钟</span></p> -->
				<p>考试时间：{{editTestList.answer_time ? editTestList.answer_time : 100}}分钟，满分{{totalNumber}}分</p>
			</div>

			<ul>
				<template v-for="(type, list) of questionTyle" >
					<li class="preview-conten-list" :key="list"  :id="'test'+type.id" >

						<div class="preview-conten-title knowledge-conten-title">
							 <span>{{type.type}}. {{type.name}}（共{{type.children.length}}题, 共{{type.score}}分 <span v-show="type.common">, {{type.common}} 。</span>）</span>
							 <el-button @click="batchSettings(1, list)">批量设置分值</el-button>
						</div>

						

						<ul class="preview-conten-subject">

							<template v-for="(item, index) of type.children" v-if="parseInt(item.qt_id) === parseInt(type.id)">
								<li :id="'test'+item.id"  class="preview-conten-subject-c"  v-if="parseInt(item.type_base_id) === 1 || parseInt(item.type_base_id) === 2 || parseInt(item.type_base_id) === 4" :key="index">

									<template>
										<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
											<i>{{item.newInx}}. </i>
											<span v-html="item.content"></span>
											<strong>({{item.score}}分)</strong>
										</div>
										<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
											<i>{{item.newInx}}. </i>
											<span v-html="item.content"></span>
											<strong v-if="item.score">({{item.score}}分)</strong>
										</div>
									</template>
									
									<ul class="preview-topic" v-if="item.option">

										<template v-for="(option,index2) of item.option" >

											<li class="preview-subject-title preview-false option-pattern" v-if="item.type_base_id === 4"  :key="index2">
												<template >
													<el-checkbox  disabled :label="option.name"></el-checkbox>
												</template>
											</li>

											<template v-else>
												<li class="preview-subject-title preview-false" v-if="item.pattern === 1" :key="index2">
													<template>
														<el-checkbox disabled :label="option.name"></el-checkbox>
														<div  v-html="option.value"></div>
													</template>
												</li>

												<li class="preview-subject-title preview-false option-pattern" v-if="item.pattern === 2"  :key="index2">
													<template >
														<el-checkbox disabled :label="option.name"></el-checkbox>
														<!-- <div  v-html="option.value"></div> -->
													</template>
												</li>
											</template>
											
										</template>

									</ul>
										

									<el-collapse accordion class="preview-answer">
										<el-collapse-item>
											<template slot="title">
												<div class="preview-accordion-title">
													<span>题型：{{item.question_type}}</span>
													<span>难度： {{item.difficulty}}</span>
													<span v-if="item.keynote == 1">重点程度： 低</span>
													<span v-if="item.keynote == 2">重点程度： 中</span>
													<span v-if="item.keynote == 3">重点程度： 高</span>
												</div>
												<div class="accordion-operate accordion-operate2" @click.stop="">
													<a @click.stop="operationQuestions(list, index, item, 1)">编辑</a>
													<a  @click.stop="operationQuestions(list, index, item, 2)">移除试题</a>
													<span  @click.stop="operationQuestions(3)">
														设定分值
														<!-- <el-input v-model="item.score" @change="scoreChange($event, list, index)" min='1' type="number" placeholder="分数"></el-input> -->

														<el-input-number @change="changeScore" style='width:auto' v-model="item.score" :controls='false' controls-position="right" :step="1" step-strictly :min="1" :max="100"></el-input-number>
													</span>
												</div>
											</template>


											<div class="preview-accordion-answer" >

												<span>正确答案： </span>
											<!-- 	<template v-if="item.qt_id == 9">
													<div v-if="item.answer"><i>{{item.answer[0]}}</i></div>
												</template> -->
												<template >
													<div><i v-for="answer of item.answer">{{answer}}</i></div>
												</template>
												
											</div>
											<div class="preview-accordion-answer">
												<span>统计： </span>
												<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
											</div>
											<div class="preview-accordion-answer">
												<span>解析： </span>
												<template v-if="item.pattern == 1">
													<div v-html="item.resolve"></div>
												</template>
												<template v-if="item.pattern == 2">
													<div>
														<img :src="BASE_URL + item.resolve_path">
													</div>
												</template>
											</div>
										</el-collapse-item>
									</el-collapse>
								</li>

								<li :id="'test'+item.id"  class="preview-conten-subject-c"  v-else  :key="index">

									<template>
										<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
											<i>{{item.newInx}}. </i>
											<span v-html="item.content"></span>
											<strong v-if="item.score">({{item.score}}分)</strong>
										</div>
										<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
											<i>{{item.newInx}}. </i>
											<span v-html="item.content"></span>
											<strong>({{item.score}}分)</strong>
										</div>
									</template>
									
									<ul class="preview-topic"  v-if="item.option">
										<li class="preview-subject-title preview-false"  v-for="(option,index2) of item.option" :key="index2">
											<template>
												<el-checkbox disabled :label="option.name"></el-checkbox>
												<div  v-html="option.value"></div>
											</template>
										</li>
									</ul>
										

									<el-collapse accordion class="preview-answer" v-if='1'>
										<el-collapse-item>
											<template slot="title">
												<div class="preview-accordion-title">
													<span>题型：{{item.question_type}}</span>
													<span>难度： {{item.difficulty}}</span>
													<span v-if="item.keynote == 1">重点程度： 低</span>
													<span v-if="item.keynote == 2">重点程度： 中</span>
													<span v-if="item.keynote == 3">重点程度： 高</span>
												</div>
												<div class="accordion-operate" @click.stop="">
													<a @click.stop="operationQuestions(list, index, item, 1)">编辑</a>
													<a  @click.stop="operationQuestions(list, index, item, 2)">移除试题</a>
													<span  @click.stop="operationQuestions(3)">
														设定分值
														<el-input-number @change="changeScore"  style='width:auto' v-model="item.score" :controls='false' controls-position="right" :step="1" step-strictly :min="1" :max="100"></el-input-number>
													</span>
												</div>
											</template>
										<!-- 	<div class="preview-accordion-answer">
												<span>正确答案： </span>
												<div>
													<i v-for="answer of item.answer">{{answer}}</i>
												</div>
											</div> -->
											<div class="preview-accordion-answer">
												<span>统计： </span>
												<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
											</div>
											<div class="preview-accordion-answer">
												<span>解析： </span>
												<template v-if="item.pattern == 1">
													<div v-html="item.resolve"></div>
												</template>
												<template v-if="item.pattern == 2">
													<div>
														<img :src="BASE_URL + item.resolve_path">
													</div>
												</template>
											</div>
										</el-collapse-item>
									</el-collapse>
								</li>
							</template>

						</ul>
					</li>
				</template>
			</ul>
			<div class="dependent" v-if="placeholder">
				<i class="ipng image_state01"></i>
				<p>还没发现任何相关的内容哦~</p>
			</div>
		</el-scrollbar>

		<div class="knowledge-outline-box">

			<div class="nav-class-r" v-if='1'>
				<span v-if="isArrow">大纲<i class="el-icon-arrow-right"></i></span>
				<span v-else>大纲<i class="el-icon-arrow-left"></i></span>
			</div>

			<input type="checkbox" name="arrow" v-model="isArrow">	
			<div class="knowledge-outline-type">
				<el-scrollbar  class="knowledge-outline-type-cont">
					<template v-for="(type, list) of questionTyle">
						<div class="" :key="list">
							<div class="knowledge-outline-ht" @dblclick="Tocontone(type.id)">
								<a>{{type.type}} . {{type.name}}</a><!-- <i></i> -->
							</div>
							<ul>
								<li class="drop" v-for="(item, index) of type.children" :key="index"
								:draggable="draggable"
								@dragstart="dragstart($event, list, index,)"
								@dragover.prevent="dragover($event)"
								@drop="drop($event, list,index, item.id)"
								@dragend="draggable=false">
									<a  @dblclick="Tocontone(item.id)">
										<strong>{{index+1}}.xxxxxx </strong>
										<div v-html="item.content" v-if="item.pattern == 1"></div>
										<div  v-else>[图片]...</div>
									</a>
									<span  @mousedown="draggable=true"><i></i><i></i><i></i></span>
								</li>
							</ul>
						</div>
					</template>
					
					
				</el-scrollbar >
				
			</div>

		</div>

		<el-dialog
		  title="批量设置分值" width="400px"
		  :visible.sync="settingsVisible"
		  custom-class="Tailoring2"
		  :close-on-click-modal="false">
		  <div class="knowledge-set-number">
		  		<div>
		  			批量设置该题型分值
		  			<el-input-number v-model="fraction"  controls-position="right" :step="1" step-strictly :min="1" :max="100"></el-input-number>
		  		</div>
		  		<p>只能填大于0的整数，如1,2,5,10等</p>
		  </div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="settingsVisible = false" type="primary" plain>取 消</el-button>
		    <el-button type="primary" v-preventReClick="1000" @click="setScore()">确 定</el-button>
		  </span>
		</el-dialog>

		<div class="knowledge-visible" v-if="testVisible">
			<el-dialog  
			  title="编辑试题" width="800px"
			  :visible.sync="testVisible"
			  custom-class="Tailoring" top="3vh"
			  :close-on-click-modal="false">
				<knowledgeVisible :test-obj="testObj" :testVisible="testVisible"></knowledgeVisible>
			</el-dialog>
		</div>

		<div v-if="newTopics" class="knowledge-visible" >
			<el-dialog  
				:append-to-body="true"
			  title="新增题目" width="800px"
			  :visible.sync="newTopics"
			  custom-class="Tailoring" top="3vh"
			  :close-on-click-modal="false">
				<knowledgeAdd  :newTopics="newTopics"></knowledgeAdd>
			</el-dialog>
		</div>

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
	</div>
</template>

<script>
	let manualObj = JSON.parse(sessionStorage.getItem('manualObj'));
	import bus  from  './../base/eventBus.js'
	import knowledgeAdd from "./knowledge-dialog-add.vue";
	import knowledgeVisible from "./knowledge-dialog.vue";
	export default {
		components: {knowledgeVisible, knowledgeAdd},
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				isArrow: false,
				radio: '',
				input: '',
				fraction: '',
				testVisible: false,    /*编辑试题*/
				settingsVisible: false, /*批量设置分值*/

				testTime:  manualObj?manualObj.duration:'',/*试卷的试卷*/
				testName: manualObj?manualObj.name:'',/*试卷的名字*/
				testScore: '',/*试卷的总分*/
				questionList: [],/*试卷的列表数组*/
				questionTyle: [],
				draggable:false,   /*控制可拖拽属性，true为能拖拽，false不能拖拽*/
				sortidx:null,    // 存放被拖拽的li索引值
				newTestArr: [], /*存放分值的数组*/


				editTestList: [], /*编辑试卷的数组列表*/
				testVisible: false,
				testObj: '',
				placeholder: true,
				newTopics:false,
				objectCont: {},

				imgIndex: 0,
				txtName: '',
				tipName: '',
				valid: false,
				scoreArr: [],
				scoreArr2: []

			}
		},
		created(){


				
				bus.$on('setTest', (showVisible)=>{

					this.testVisible = false;
					this.newTopics = false
				})

				/*bus.$on('addTest', (obj)=>{
					// this.newTopics = false
					// this.editTest()
				})*/
		},
		watch: {
			'$store.state.questionChange': {
				handler(val, newval){
					this.editTest()
				},
				immediate: true
			},
			// 所有题目要按顺序排列，此处自定义一个序列号newInx
			'questionTyle':{
				handler(newVal, newval){
					let inx = 0;
					for (let i = 0; i < newVal.length; i++) {
						const item = newVal[i];
						for (let j = 0; j < item.children.length; j++) {
							let child = item.children[j];
							inx++;
							child.newInx = inx;
						}
					}
				},
				deep: true
			}
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			},
			totalNumber(){
				let number = 0
				this.questionTyle.forEach(item=>{
					item.children.forEach(list=>{
						number += parseInt(list.score)
					})
				})

				return number 
			}
		},
		mounted(){
			this.$nextTick(()=>{
				document.querySelector('.r-r').addEventListener('click',  (e)=> {
					
					let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
					if (e.target.nodeName === 'IMG') {

						this.imagePreview.showViewer = true
						targetSrc = e.target.src;
						imgs = [...e.target.parentNode.children];
						srcArr = imgs.map(item=>item.currentSrc);
						currentIdx = srcArr.indexOf(targetSrc);

						this.imagePreview.previewSrcList = srcArr
						this.imgIndex = targetSrc

					}
					
				}, false)

			
			});
		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			/**
			 * 试卷的试题排序 && 设定分值 
			 * @DateTime 2019-08-13T15:27:53+0800
			 * @return   {[type]}                 [description]
			 */
			testChang(){
				let [idex, questionList] = [1, []]

				this.questionTyle.forEach(item=>{
					item.children.forEach(list=>{
						questionList.push({
							'question_id': list.id,
							'score': list.score,
							'sort': idex++
						})
					})
				})

				let success = (res=>{
					this.editTest()
					// this.$message.success(res.msg);
				});

			

				let params = {test_id: this.$route.query.id || this.$route.query.edit, question_list: questionList};
				this.$ajax.put('api/newtest/change_test', params, {func: {success: success}})
			},
			changeScore(val){
				if (val) {
					this.testChang()
				}
			},
			/*大纲的锚点滚动*/
			Tocontone(id){
				let elment = '#test'+id
				let anchor = document.querySelector(elment)
				anchor.classList.add('styleCss')
				var bar = this.$refs['elscrollbar'].$refs['wrap'];
				this.$nextTick(() => {
					bar.scrollTop = anchor.offsetTop - 10;
				})

				setTimeout(()=>{

					anchor.classList.remove('styleCss')
				},1000);



			},
			/*修改试卷名字*/
			setTestName(){

				if (this.testName == '') {
					// this.testName = this.txtName 
					this.valid = true
					this.tipName = '标题名不能为空'
					return 
				} else if (this.testName.length < 3) {
					this.tipName = '长度在3到20个字符'
					this.valid = true
					return 
				}else{
					this.tipName  = ''
					this.valid = false
				}

				this.$store.commit('SET_TESTNAME', this.testName)
				let success = (res =>{
					// this.$message.success(res.msg);
				});

				let params = {
					create_id: this.$g.user_id,
					id: this.$route.query.id || this.$route.query.edit,
					name: this.testName,
					status: 1,
				};

				this.$ajax({
					url: 'api/newtest/save_test',
					method: 'put',
					data: params,
					func: {success: success}
				})
			},
			/**
			 * 请求编辑试卷的列表
			 * @DateTime 2019-08-15T10:49:23+0800
			 * @return   {[type]}                 [description]
			 */
			editTest(){
				let success = (res=>{

					let total = 0;

					let manualObj = {
						grade: res.data.grade_id ? res.data.grade_id : '',		/*年级*/
						subject: res.data.subject_id ? res.data.subject_id : '',	/*学科*/
						edition: res.data.version_id ? res.data.version_id : '',	/*版本*/
						course_id: res.data.course_id ? res.data.course_id : '',/*教材*/
						type: res.data.source_id ? res.data.source_id : '',		/*试卷类型*/
						authType: res.data.auth_type ? res.data.auth_type : 1		/*试卷组卷类型 1章节 2知识点*/
						// material: res.data.version_id
					};

					sessionStorage.setItem('manualObj', JSON.stringify(manualObj))

					this.editTestList = res.data;
					this.testName = res.data.name
					this.txtName = res.data.name
					this.questionTyle = []
					this.editTestList.question_type.forEach((item=>{
						total += parseInt(item.score);
						this.questionTyle.push({
							id: item.id,
							name: item.question_type,
							type: item.cn_num,
							score: item.score,
							children: []
						})

					}));
					this.testScore = total;
					this.editTestList.question_list.forEach((item, index)=>{
						this.questionTyle.forEach((list, index2)=>{
							if (list.id === item.qt_id) {
								let html = item.content.match(/<p>.*?<\/p>/g)
								list.children.push(item)
							}
						})
					})

					bus.$emit('array', this.editTestList.question_list)

					this.questionTyle.length != 0 ? this.placeholder = false : this.placeholder = true
					
					this.titleShow()
			
					bus.$emit('setQuestion', this.questionTyle);
				});
				let params = ''
				if (this.$route.query.edit) {
					 params = {
						id: this.$route.query.edit,
						user_id: this.$g.user_id
					};
				}else if (this.$route.query.points) {
					 params = {
						id: this.$route.query.id,
						user_id: this.$g.user_id
					};
				}

				this.$ajax({
					url: 'api/newtest/test_detail',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},

			titleShow(){
				/*改变大纲title显示问题*/
				this.$nextTick(()=>{
					let html = document.querySelectorAll('.drop>a p')

					html.forEach((item, index)=>{
						// let text = item
						/*空格的p标签*/
						if (item.innerHTML == '<br>') {
							item.className += ' line-txt'
							
						}else{
							/*p标签包含img*/
							item.childNodes.forEach(node=>{
								if (node.nodeName === 'IMG') {
									item.innerHTML = '[图片]...'
								}
							})
						}
					})
				})
			},
			// ===============拖拽的方法================
			// 拖拽开始事件
			dragstart(e,idx, idx2){
				e.dataTransfer.setData("drag",'drag');
				this.sortidx = idx2;
				if ( event.target.className == "drop" ) {
					event.target.style.backgroundColor = "#98c6ff";

				}

			},
			// 拖拽方式事件
			drop(e,idx, idx2){
				// console.log("被拖拽排序的li索引值：",this.sortidx,"被放置的li索引值：",idx2)

				let obj = this.questionTyle[idx].children[this.sortidx];
				this.questionTyle[idx].children.splice(this.sortidx, 1)
				this.questionTyle[idx].children.splice(idx2, 0, obj);
				this.titleShow()
				bus.$emit('setQuestion', this.questionTyle);
			},
			dragover(e){
				if ( event.target.className == "drop" ) {
				     event.target.style.backgroundColor = "";
				}
			},

			// ===============拖拽的方法================
			setQuestion(){
				
				bus.$on("testChange", (questionArray) => {
					this.questionList  = []
					this.questionList = deep_clone(questionArray)

					

					if (this.$route.query.edit) {/*编辑试卷*/

	
						this.questionList.forEach((list,index2)=>{

							this.questionTyle.forEach((item,index)=>{

								if (list.qt_id == item.id ) {

									let flas = true;//临时变量
									item.children.forEach(child=>{
										if ( list.id == child.id ) {
											flas= false// 两个数组的 id 相等时，flas = false，筛选出两个数组不相等的 id
										}
									})
									//筛选出两个数组不相等的 id push到数组里面
									if (flas) {
										item.children.push(list)
									}
								}
							})

						})
						
						//根据状态参数删除试题
						if (this.$store.state.questionChange) {
							this.questionTyle.forEach((item,index)=>{
								item.children.forEach((list, index2) =>{
									if ( list.id == this.$store.state.questionChange) {
										item.children.splice(index2, 1)
									}
								})
							})
						}
					}else{ /*手动组卷*/
						this.questionTyle = [];
						let listArr = [];/*新建-试卷的新数组*/
						let typeArr = ['0', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六']; /*新建-试卷的中文123*/
						let idArray = [] /* 试卷的类型 id, 用来添加试题对象并去重*/

						this.questionList.forEach((item, index)=>{

							if (!idArray.includes(item.qt_id)) {

								listArr.push({
									id: item.qt_id,
									name: item.question_type,
									type: typeArr[item.qt_id],
									children: []
								})
							}

							idArray.push(item.qt_id)
							idArray = [...new Set(idArray)]

							listArr.forEach((item2, index2) =>{
								if (item2.id === item.qt_id) {
									listArr[index2].children.push(item)
								}
							})
						});
						/*根据 id 升序排序试卷*/
						this.questionTyle = listArr.sort(this.reSort('id'));
					}

					bus.$emit('setQuestion', this.questionTyle);

				});
			},
			/**
			 * 重新排序试卷
			 * @DateTime 2019-08-12T09:38:37+0800
			 * @param    {[type]}                 arr   [description]
			 * @return   {[type]}                       [description]
			 */
			 reSort(arr){

			 	return function(a,b){
			 		var value1 = a[arr];
			 		var value2 = b[arr];
			 		return value1 - value2;
			 	}
			 },
			/**
			 * type 参数对应不同的函数，
			 *
			 * 1.编辑
			 * 2.移除试题
			 * 3.设定分值
			 */
			operationQuestions(list, index, obj, type){
				this.objectCont = obj
				switch(type){
					case 1:
                        this.testObj = obj;
                        this.testVisible = true;
						break;

					case 2:

						this.$confirm('确定要将该试题从本试卷移除么？', '提示', {
							cancelButtonText: '取消',
							confirmButtonText: '确定',
							type: 'warning',
							customClass: "test-message"
						}).then(() => {
							// console.log(obj.pid, 'r')
							let success = (res=>{
								this.$message.success(res.msg)
								this.$store.commit('SET_DELQUESTION', obj.pid)
								this.editTest()
							})
							 let params = '';

							 if (this.$route.query.id) {
							 	params = {
							 		testid: this.$route.query.id,
							 		question_id: obj.id
							 	}
							 }else{
							 	params  = {
							 		testid: this.$route.query.edit,
							 		question_id: obj.id
							 	}
							 }
							this.$ajax({
								url: 'api/test/bind_one_question_to_test',
								method: 'delete',
								params: params,
								func: {success: success}
							})

						}).catch(() => {});
						break;
					case 3:
						break;
				}
			},
			/**
			 * type 参数对应不同的试题类型，
			 */
			batchSettings(type, index){
				this.settingsVisible = true;
				this.newTestArr = this.questionTyle[index]
			},
			/**
			 * 批量设置分值
			 * @DateTime 2019-08-13T14:37:49+0800
			 */
			setScore(){
				if (this.fraction == 0) {
					return this.$message.error("分值不能为0")
				}
				this.newTestArr.children.forEach((item)=>{
					item.score = this.fraction
				});
				this.settingsVisible = false;
				this.$message.success("设置分值成功")
				this.testChang()
			},
			/**
			 * 设定分值
			 * @DateTime 2019-08-13T14:38:30+0800
			 * @param    {[type]}                 val    [description]
			 * @param    {[type]}                 index  [description]
			 * @param    {[type]}                 index2 [description]
			 * @return   {[type]}                        [description]
			 */
			scoreChange(val, index, index2){
				this.questionTyle[index].children[index2].id = val;
				this.settingsVisible = false;
				// this.$message.success("设置分值成功")
			},
			/**
			 * 新增自建题目
			 */
			newTopic(){
				this.newTopics = true
				sessionStorage.setItem('addTS', this.newTopics)
			}
		}
	}
</script>